public class Solution {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public int i = 0;
    public TreeNode buildTree(int[] preorder,int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length);
    }
    public TreeNode buildTreeChild(int[] preorder,int[] inorder,int begin,int end) {
        if (begin > end) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[i]);
        int rootIndex = findIndex(inorder,begin,end,preorder[i]);
        i++;
        root.left = buildTreeChild(preorder,inorder,begin,rootIndex-1);
        root.right = buildTreeChild(preorder,inorder,rootIndex+1,end);
        return root;
    }
    public int findIndex(int[] inorder,int begin,int end,int key) {
        for (int k = begin ; k <= end; k++) {
            if (key == inorder[k] ) {
                return k;
            }
        }
        return -1;
    }
}
